<template>
  <canvas
    ref="canvas"
    :key="unique"
    :width="width"
    :height="height"
    @click="refresh"
  />
</template>

<script>
import _ from 'lodash';

export default {
  name: 'Verfiy',
  data() {
    return {
      unique: _.uniqueId(),
      code: '',
      width: '120',
      height: '42',
      numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
      ctx: null
    };
  },
  mounted() {
    this.init();
  },
  updated() {
    this.init();
  },
  methods: {
    init() {
      this.code = '';
      this.ctx = this.$refs.canvas.getContext('2d');
      this.ctx.textBaseline = 'middle';
      this.ctx.fillStyle = this.randomColor(180, 240);
      this.ctx.fillRect(0, 0, this.width, this.height);
      this.fillNumber();
      // this.fillLines();
      // this.fillPoints();

      this.$emit('code', this.code);
    },
    refresh() {
      this.unique = _.uniqueId();
    },
    randomColor(min, max) {
      const r = _.random(min, max);
      const g = _.random(min, max);
      const b = _.random(min, max);
      return `rgb(${r},${g},${b})`;
    },
    fillLines() {
      for (let i = 0; i < 4; i += 1) {
        this.ctx.strokeStyle = this.randomColor(40, 180);
        this.ctx.beginPath();
        this.ctx.moveTo(_.random(0, this.width), _.random(0, this.height));
        this.ctx.lineTo(_.random(0, this.width), _.random(0, this.height));
        this.ctx.stroke();
      }
    },
    fillPoints() {
      for (let i = 0; i < 10; i += 1) {
        this.ctx.fillStyle = this.randomColor(0, 255);
        this.ctx.beginPath();
        this.ctx.arc(
          _.random(0, this.width),
          _.random(0, this.height),
          1,
          0,
          2 * Math.PI
        );
        this.ctx.fill();
      }
    },
    fillNumber() {
      for (let i = 1; i <= 4; i += 1) {
        const a = _.random(0, this.numbers.length - 1);
        const txt = this.numbers[a];
        this.code += txt;
        this.ctx.font = `${_.random(this.height / 2, this.height)}px SimHei`; // 随机生成字体大小
        this.ctx.fillStyle = this.randomColor(50, 160); // 随机生成字体颜色
        // this.ctx.shadowOffsetX = _.random(-3, 3);
        // this.ctx.shadowOffsetY = _.random(-3, 3);
        this.ctx.shadowBlur = _.random(-3, 3);
        this.ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
        const x = (this.width / 5) * i;
        const y = this.height / 2;
        const deg = _.random(-30, 30);
        /** 设置旋转角度和坐标原点* */
        this.ctx.translate(x, y);
        this.ctx.rotate((deg * Math.PI) / 180);
        this.ctx.fillText(txt, 0, 0);
        /** 恢复旋转角度和坐标原点* */
        this.ctx.rotate((-deg * Math.PI) / 180);
        this.ctx.translate(-x, -y);
      }
    }
  }
};
</script>
